package com.ld.poetry.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ld.poetry.aop.LoginCheck;
import com.ld.poetry.config.PoetryResult;
import com.ld.poetry.dao.MusicMapper;
import com.ld.poetry.entity.Music;
import com.ld.poetry.service.MusicService;
import com.ld.poetry.vo.MusicVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 只能登录管理员账号后才能使用
 */
@RestController
@RequestMapping("/play")
public class PlayMusicController {

    @Autowired
    private MusicService musicService;

    @Autowired
    private MusicMapper musicMapper;
    /**
     * 分页查询音乐播放列表--根据歌手名称、歌手类型、歌曲名称查询
     */
    @PostMapping("/musicList")
    @LoginCheck(0)
    public PoetryResult<Page> listMusic(@RequestBody MusicVo musicVo) {
        return musicService.listMusic(musicVo);
    }

    /**
     *  保存/更新音乐信息
     */
    @PostMapping("/saveMusic")
    @LoginCheck(0)
    public PoetryResult saveMusic(@RequestBody Music music) {
        QueryWrapper<Music> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", music.getName())
                .eq("artist", music.getArtist());

        Music existingMusic = musicMapper.selectOne(queryWrapper);

        if (music.getId() == null) {
            // 在新增时判断检查是否在曲库中重复
            if (existingMusic != null) {
                return PoetryResult.fail("歌曲已存在");
            }
            music.setCreateTime(LocalDateTime.now());
            musicMapper.insert(music);
        } else {
            music.setUpdateTime(LocalDateTime.now());
            musicMapper.updateById(music);
        }
        return PoetryResult.success();
    }

    /**
     *  删除音乐信息
     */
    @DeleteMapping("/deleteMusic/{id}")
    @LoginCheck(0)
    public PoetryResult deleteMusic(@PathVariable Integer id) {
        return musicService.deleteMusic(id);
    }

    @GetMapping("/getMusicById")
    @LoginCheck(0)
    public PoetryResult getMusicById(@RequestParam Integer id) {
        return PoetryResult.success(musicService.getById(id));
    }

    /**
     *  查询全部歌曲信息
     */
    @PostMapping("/getMusicList")
    @LoginCheck(0)
    public PoetryResult getMusicList(@RequestBody MusicVo musicVo) {
        if (musicVo == null) {
            return PoetryResult.success(musicService.list());
        } else {
            return PoetryResult.success(musicService.selectMusic(musicVo));
        }
    }
}